package database;

import com.mysql.jdbc.PreparedStatement;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;

/**
 * Created with IntelliJ IDEA.
 * User: leep
 * Date: 15-12-24
 * Time: 下午4:31
 * To change this template use File | Settings | File Templates.
 */
public class JDBCInsert {
	public static void main(String args[]) {
		Connection conn = null;
		java.sql.PreparedStatement pstmt = null;
		try {
			Class.forName(DBConf.JDBC_DRIVER);
			conn = DriverManager.getConnection(DBConf.DB_URL, DBConf.USER, DBConf.PASS);

			String sql = "INSERT INTO users(name, age) VALUES(?,?)";
			pstmt = conn.prepareStatement(sql);
			// insert a user
			pstmt.setString(1, "letian");
			pstmt.setInt(2, 18);
			pstmt.execute();
			// insert another user
			pstmt.setString(1, "letiantian");
			pstmt.setInt(2, 19);
			pstmt.execute();

			//select
			sql = "SELECT * FROM users";
			pstmt = conn.prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getInt("id"));
				System.out.println(rs.getString("name"));
				System.out.println(rs.getInt("age"));
				System.out.println("------");
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}


	}
}
